import 'dart:math';
import 'package:flutter/material.dart';
import 'package:mathfun/pages/dot_flash_training_result_page.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dot_training_result_page.dart';

class DotFlashTrainingPage extends StatefulWidget {
  @override
  _DotFlashTrainingPageState createState() => _DotFlashTrainingPageState();
}

class _DotFlashTrainingPageState extends State<DotFlashTrainingPage>
    with WidgetsBindingObserver {
  int currentQuestion = 1;
  int totalQuestions = 10;
  int dotCount = 0;
  int redDotCount = 0;
  int blueDotCount = 0;
  List<Offset> dotPositions = [];
  List<Color> dotColors = [];
  bool dotsVisible = true;
  late DateTime questionStartTime;
  List<int> responseTimes = [];
  List<bool> correctness = [];
  Map<int, List<int>> numberResponseTimes = {};
  BoxConstraints? _dotContainerConstraints;
  String currentQuestionType = '';
  int correctAnswer = 0;
  List<int> _previousRedDotCounts = [];
  List<int> _previousBlueDotCounts = [];

  // 配置参数
  int minDotCount = 4;
  int maxDotCount = 10;
  double flashDuration = 4;
  double dotRadius = 10.0;

  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    if (mounted) {
      setState(() {
        totalQuestions = prefs.getInt('dotFlashTrainingQuestions') ?? 10;
        flashDuration = prefs.getInt('dotFlashDisplayDuration')?.toDouble() ?? 2.0;
        minDotCount = prefs.getInt('dotFlashMinDots') ?? 8;
        maxDotCount = prefs.getInt('dotFlashMaxDots') ?? 12;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadSettings().then((_) {
      if (_dotContainerConstraints != null && mounted && dotPositions.isEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted && dotPositions.isEmpty && _dotContainerConstraints != null) {
            _generateNewQuestion(_dotContainerConstraints!);
          }
        });
      }
    });
  }

  @override
  void didPopNext() {
    _resetTraining();
  }

  void _resetTraining() {
    setState(() {
      currentQuestion = 1;
      responseTimes.clear();
      correctness.clear();
      numberResponseTimes.clear();
      dotPositions.clear();
      dotColors.clear();
    });
    if (_dotContainerConstraints != null) {
      _generateNewQuestion(_dotContainerConstraints!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('数点快闪训练')),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: Text(
              '题目 $currentQuestion / $totalQuestions',
              style: TextStyle(fontSize: 20),
            ),
          ),
          Divider(),
          Expanded(
            flex: 3,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.55,
                minHeight: 280,
              ),
              child: LayoutBuilder(
                builder: (context, constraints) {
                  _dotContainerConstraints = constraints;
                  if (dotPositions.isEmpty && constraints.maxWidth > 0) {
                    WidgetsBinding.instance.addPostFrameCallback((_) {
                      if (mounted && dotPositions.isEmpty) {
                        _generateNewQuestion(constraints);
                      }
                    });
                  }
                  return Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.surfaceVariant,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Stack(
                      children: [
                        if (dotsVisible) ...dotPositions.asMap().entries.map((entry) {
                          int index = entry.key;
                          Offset pos = entry.value;
                          return Positioned(
                            left: pos.dx,
                            top: pos.dy,
                            child: Container(
                              width: dotRadius * 2,
                              height: dotRadius * 2,
                              decoration: BoxDecoration(
                                color: dotColors[index],
                                shape: BoxShape.circle,
                              ),
                            ),
                          );
                        }).toList(),
                        if (!dotsVisible) Center(
                          child: Text(
                            currentQuestionType,
                            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ),
          Expanded(
            flex: 5,
            child: LayoutBuilder(
              builder: (context, constraints) {
                final crossAxisCount = (constraints.maxWidth / 120).floor().clamp(3, 5);
                return GridView.count(
                  crossAxisCount: crossAxisCount,
                  mainAxisSpacing: 10,
                  crossAxisSpacing: 10,
                  padding: EdgeInsets.all(16),
                  childAspectRatio: 1.2,
                  children: List.generate(15, (i) => i + 1)
                      .map((number) => Container(
                            margin: EdgeInsets.all(4),
                            child: ConstrainedBox(
                              constraints: BoxConstraints(
                                minWidth: 80,
                                maxWidth: 120,
                                minHeight: 50,
                                maxHeight: 70,
                              ),
                              child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  padding: EdgeInsets.symmetric(vertical: 8),
                                  textStyle: TextStyle(fontSize: 18),
                                  minimumSize: Size(60, 60),
                                ),
                                child: Text('$number'),
                                onPressed: !dotsVisible ? () => _checkAnswer(number) : null,
                              ),
                            ),
                          ))
                      .toList(),
                );
              },
            ),
          )
        ],
      ),
    );
  }

  void _generateNewQuestion(BoxConstraints drawingAreaConstraints) {
    final rand = Random();
    dotCount = rand.nextInt(maxDotCount - minDotCount + 1) + minDotCount;
    redDotCount = rand.nextInt(dotCount - 1) + 1;
    blueDotCount = dotCount - redDotCount;
    dotPositions.clear();
    dotColors.clear();

    // 生成红色圆点
    for (int i = 0; i < redDotCount; i++) {
      dotColors.add(Colors.red);
    }
    // 生成蓝色圆点
    for (int i = 0; i < blueDotCount; i++) {
      dotColors.add(Colors.blue);
    }
    // 打乱颜色顺序
    dotColors.shuffle();

    final double containerWidth = drawingAreaConstraints.maxWidth;
    final double containerHeight = drawingAreaConstraints.maxHeight;
    final double internalPadding = 16.0;

    final double minX = internalPadding;
    final double maxX = containerWidth - internalPadding - dotRadius * 2;
    final double minY = internalPadding;
    final double maxY = containerHeight - internalPadding - dotRadius * 2;

    if (maxX <= minX || maxY <= minY) {
      print('Warning: Dot drawing area is too small');
      if (mounted) setState(() {});
      return;
    }

    double adjustedMinDistance = max(40.0, dotRadius * 2.5);
    if (dotCount > 5) {
      adjustedMinDistance = max(adjustedMinDistance * 0.8, dotRadius * 2.0);
    }

    int maxAttemptsPerDot = 200;

    for (int i = 0; i < dotCount; i++) {
      bool pointPlaced = false;
      int attempts = 0;
      while (attempts < maxAttemptsPerDot && !pointPlaced) {
        final candidate = Offset(
          minX + rand.nextDouble() * (maxX - minX),
          minY + rand.nextDouble() * (maxY - minY),
        );

        bool tooClose = false;
        for (final existing in dotPositions) {
          final distance = (existing - candidate).distance;
          if (distance < adjustedMinDistance) {
            tooClose = true;
            break;
          }
        }

        if (!tooClose) {
          dotPositions.add(candidate);
          pointPlaced = true;
        }
        attempts++;
      }

      if (!pointPlaced) {
        print('Warning: Could not place all dots. Placed \$i out of \$dotCount');
        break;
      }
    }

    setState(() {
      dotsVisible = true;
      // 移除条件判断，记录所有题目的点数数据
      _previousRedDotCounts.add(redDotCount);
      _previousBlueDotCounts.add(blueDotCount);
    });

    // 设置闪现定时器
    Future.delayed(Duration(milliseconds: (flashDuration * 1000).round()), () {
      if (mounted) {
        setState(() {
          dotsVisible = false;
          _generateQuestionType();
          questionStartTime = DateTime.now();
        });
      }
    });
  }

  void _generateQuestionType() {
    final rand = Random();
    final questionTypes = [
      {'text': '红色圆点有几个？', 'answer': redDotCount},
      {'text': '蓝色圆点有几个？', 'answer': blueDotCount},
      {'text': '总共有几个点？', 'answer': dotCount},
    ];
    final selectedQuestion = questionTypes[rand.nextInt(questionTypes.length)];
    setState(() {
      currentQuestionType = selectedQuestion['text'] as String;
      correctAnswer = selectedQuestion['answer'] as int;
    });
  }

  void _checkAnswer(int userAnswer) {
    final responseTime = DateTime.now().difference(questionStartTime).inMilliseconds;
    responseTimes.add(responseTime);
    final isCorrect = userAnswer == correctAnswer;
    correctness.add(isCorrect);

    if (currentQuestion >= totalQuestions) {
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => DotFlashTrainingResultPage(
              totalQuestions: totalQuestions,
              correctCount: correctness.where((c) => c).length,
              responseTimes: responseTimes,
              // 
              correctness: correctness,
            ),
          ),
        );
    } else {
      setState(() {
        currentQuestion++;
      });
      _generateNewQuestion(_dotContainerConstraints!);
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}